/**
 * 创建异步队列
 * **/
export class Queue {
  constructor () {
    this.task = []
  }

  next (fn) {
    this.task.push(fn)
    return this
  }

  exec () {
    return new Promise((resolve, reject) => {
      const loop = (i, ctx) => {
        const fn = this.task[i]
        fn(ctx, (err, res) => {
          if (err) return reject(err)

          ctx.push(res)

          if (i < (this.task.length - 1)) {
            loop(i + 1, ctx)
          } else {
            resolve(ctx)
          }
        })
      }

      if (this.task.length === 0) {
        resolve([])
      } else {
        loop(0, [])
      }
    })
  }
}

const queue = new Queue()

queue.next(function () {})

